<template>
	<view>
		<u-navbar :title="title" :autoBack="true" :placeholder="true"></u-navbar>
		<view class="is_show">
			<view class="is_show1">
				<view class="is_show_dian"></view>
				<view class="is_show_text">
					{{
						is_online===0?'离线':
						is_online===1?'在线':
						is_online===2?'隐身':''
					}}
				</view>
			</view>
		</view>
		<view>
			<scroll-view class="scroll_view" scroll-y="true" 
				:scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			  :scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="50">
				<view class="scroll_view_view">
					<view class="scroll_view_item"
					v-for="(item, index) in msgList"
					:key="index"
					:id="item.ID">
						<!-- 自己发出的消息 -->
						<view class="dialogue_list list_right" v-if="item.flow == 'out'">
							<view v-if=" item.type==TIM.TYPES.MSG_TEXT "
							class="dialogue_list_right dialogue_list_item blok">{{ item.payload.text }}</view>
							<view v-if="item.type=='TIMCustomElem'"
								style="font-size: 0;margin-top: 40rpx;" class="">
								<image @load="imgLoad" style="width: 400rpx"
									:src="ImgUrl+item.payload.data" mode="widthFix"></image>
							</view>
						</view>
						<!-- 其他人发出的消息 -->
						<view class="dialogue_list list_left" v-if="item.flow != 'out'">
							<view class="dialogue_list_left dialogue_list_item">
								<!-- 左-头像 -->
								<view class="dialogue_list_left_ff">
									<image class="dialogue_list_left_img" :src="(item.avatar.indexOf(ImgUrl)==-1)?ImgUrl+item.avatar:item.avatar" mode=""></image>
									<!-- {{item.name}} -->
								</view>
								<!-- 文字消息 -->
								<view class="dialogue_list_left_text" v-if=" item.type==TIM.TYPES.MSG_TEXT ">
									<view class="blok">
										{{ item.payload.text }}
									</view>
								</view>
								<view v-if="item.type=='TIMCustomElem'"
									style="font-size: 0;margin-top: 40rpx;" class="">
									<image @load="imgLoad" style="width: 400rpx"
										:src="ImgUrl+item.payload.data" mode="widthFix"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="bottom_view">
			<input :disabled="(roomType==2)||(isEndTime)" type="text" class="bottom_view_input" placeholder="输入内容开始聊天" v-model="textMsg" />
			<view class="bottom_view_btn_active" v-if="textMsg && roomType!=2" @tap="send">发送</view>
			<view class="bottom_view_btn_active" v-if="!textMsg && roomType!=2" @click="getImage">图片</view>
			<view class="bottom_view_btn_active" v-if="roomType==2" @click="call">call</view>
		</view>

		<u-count-down v-if="getTime!=0" :time="getTime * 1000"
		format="HH:mm:ss"
		autoStart millisecond
		@change="onChange">
			<view class="time">
				<view class="time__custom">
					<text class="time__custom__item">{{ timeData.hours > 9 ? timeData.hours : '0' + timeData.hours }}</text>
				</view>
				<text class="time__doc">:</text>
				<view class="time__custom">
					<text class="time__custom__item">{{ timeData.minutes> 9 ? timeData.minutes : '0' + timeData.minutes }}</text>
				</view>
				<text class="time__doc">:</text>
				<view class="time__custom">
					<text class="time__custom__item">{{ timeData.seconds> 9 ? timeData.seconds: '0' + timeData.seconds }}</text>
				</view>
				<view class="time__jieshu">后结束</view>
			</view>
		</u-count-down>
	</view>
</template>
<script>
import tim from '@/utils/tim.js'
import { mapState } from "vuex";
import { chat_content,del_unread } from "@/api/common" //接口
import uploadImage from '@/common/ossutil/ossutil/uploadFile.js';
var that
export default {
	data() {
		return {
			id:'',//会诊id
			conversationActive:'',
			//TIM变量
			group_id:'',//群聊id
			userInfo:null,
			nextReqMessageID:'',
			count:15,
			msgList:[],
			TIM:null, 
			userId:'',//自己的用户id
			pages:{
				page:1,
				size:15,
				totalPage:null
			},
			//消息列表
			isHistoryLoading:false,
			scrollAnimation:false,
			scrollTop:0,
			scrollToView:'',
			msgImgList:[],
			group_id: '',
			textMsg: '',
			show: false,
			timert: null,
			li_index: 0,
			price: '',
			ai_img: '',
			title: '',
			is_online:-1,
			roomType: -1, //类型，1图文2视频3飞刀4多人问诊
			endTime: 0, //首页列表结束时间
			isEndTime: false, //是否限制发送消息
			pay_lsit: [],
			teacher_id: '',
			ai_list_id: '',
			can_send: true,
			timeData: {}
		};
	},
	computed:{
		...mapState(["currentMessageList"]),
		ImgUrl(){
			return this.$store.state.ImgUrl
		},
		getTime() {
			// this.endTime = 1699345896;
			let nowTime = parseInt(Date.now() / 1000);
			console.log(nowTime - this.endTime);
			return this.endTime - nowTime > 0 ? this.endTime - nowTime : 1;
			// return 20;
		},
	},
	watch:{
		currentMessageList(newVal,oldVal){
			console.log(newVal,'123123123123')
			this.msgList = newVal
			this.screenMsg(newVal,oldVal)
		},
	},
	onLoad(options) {
		that = this
		this.group_id = decodeURIComponent(options.group_id)
		this.$store.commit('createConversationActive', this.group_id)
		if(options.id){
			this.id = options.id
			this.getList()
		}
		let userinfo = uni.getStorageSync('userinfo')
		if(!userinfo.id) return
		this.userId = String(userinfo.id)
		// this.loginTM()
		this.TIM = this.$TIM
		//获取聊天对象的用户信息---有后端的情况这里 使用后端api请求、
	},
	onShow(){
		this.scrollTop = 9999999;
		this.isHistoryLoading = false;
	},
	onUnload(){
		//退出页面 将所有的会话内的消息设置为已读
		console.log(this.group_id)
		del_unread({
			group_id:this.group_id
		}).then(res=>{
			console.log(res,'cs');
		})
		// console.log(typeof this.group_id)
		// let promise = this.$tim.setMessageRead({conversationID: 'GROUP' + this.group_id});
		// promise.then(function(imResponse) {
		// 	console.log('全部已读')
		// 	// 已读上报成功
		// }).catch(function(imError) {
		// 	// 已读上报失败
		// 	let promises = this.$tim.getConversationList();
		// 	promises.then(function(res) {
		// 		// 全量的会话列表，用该列表覆盖原有的会话列表
		// 		this.$store.commit("updateConversationList", res.data);
		// 		console.warn('getConversationList error:------------------imError2', res);
		// 	}).catch(function(imError) {
		// 		// 获取会话列表失败的相关信息
		// 		console.warn('getConversationList error:------------------imError', imError);
		// 	});
		// 	console.warn('setMessageRead error:', imError);
		// });
	},
	methods: {
		// 拨打电话
		call(){
			if (!this.can_send) {
				return;
			}
			if (this.isEndTime) {
				return;
			}
			this.$TUICallKit.call({
			    userID: this.doctor_id.toString(),
			    type: 2
			}).then(res=>{
				console.log(res,'cs');
			}).catch(res=>{
				console.log(res,'cs2');
			})
		},
		onChange(e) {
			if(e.days==1){
				e.hours+=24;
			}
			this.timeData = e;
			// console.log(e);
			if (e.days == 0 && e.hours == 0 && e.minutes == 0 && e.seconds == 0) {
				this.isEndTime = true;
			}else{
				this.isEndTime = false;
			}
		},
		getList(){
			let params = {
				source:2,
				id:this.id,
				...this.pages
			}
			chat_content(params).then(res=>{
				console.log(res,'cs-cs');
				if(res.code==200001){
					this.pages.totalPage = res.data.content.last_page
					this.doctor_id = res.data.doctor_id[0];
					this.title = res.data.group_name;
					this.is_online = res.data.is_online;
					this.roomType = res.data.type;
					this.endTime = res.data.service_end_time;
					let list = [];
					 res.data.content.data.map(item=>{
						item.flow = item.user_id==this.userId?'out':'into'
						item.type = item.content[0].MsgType
						item.ID = 'scroll'+item.id
						if(item.type=="TIMCustomElem"){
							item.payload = {
								data:item.content[0].MsgContent.Data
							}
						}else{
							item.payload = {
								text:item.content[0].MsgContent.Text
							}
						}
						
						list.unshift(item)
					})
					if(this.pages.page==1){
						this.$store.commit('pushCurrentMessageList', list)
					} else {
						this.isHistoryLoading = false
						this.$store.commit('unshiftCurrentMessageList', list)
					}
				} else {
					this.$showToast(res.message)
				}
			})
		},
		// loginTM(){
		// 	let res = tim.genTestUserSig(this.userId)
		// 	let promise = this.$tim.login({
		// 		userID: this.userId,
		// 		userSig: res.userSig
		// 	});
		// 	promise.then((res) => {
		// 		//登录成功后 更新登录状态
		// 		that.$store.commit("toggleIsLogin", true);
		// 		//tim 返回的用户信息
		// 		uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
		// 	}).catch((err) => {
		// 		console.warn('login error:', err); // 登录失败的相关信息
		// 	});
		// },
		send() {
			let t = this;
			if(!t.textMsg) return
			let msg = {text:t.textMsg}
			this.sendMsg(msg,'text');
			this.textMsg = ''
		},
		//聊天的节点加上外层的div
		nodesFliter(str){
			let nodeStr = '<div style="align-items: center;word-wrap:break-word;">'+str+'</div>' 
			return nodeStr
		},
		// 接受消息(定位消息)
		screenMsg(newVal,oldVal){
			if(newVal[0] && oldVal[0]){
				if(newVal[0].ID != oldVal[0].ID && newVal.length>=oldVal.length ){	
					// let _index = newVal.length-oldVal.length-1
					// this.$nextTick(()=> {this.scrollToView = newVal[_index].ID});
					// console.log(this.scrollToView)
					//拉取历史记录不用改变定位消息
				} else {
					//新的消息来了 自动向下滑动到最新消息
					this.$nextTick(()=> { this.scrollToView = newVal[newVal.length-1].ID })
				}
			} else {
				if(newVal.length){
					this.$nextTick(()=> {
						this.scrollToView = newVal[newVal.length-1].ID
						this.scrollAnimation = true;
					})
				}
			}
		},
		//触发滑动到顶部(加载历史信息记录)
		loadHistory(e){
			this.pages.page++
			const {page,totalPage} = this.pages
			if (page <= totalPage) {
				this.isHistoryLoading = true;
				this.getList()
			}
		},
		//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
		setPicSize(content){
			// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
			let maxW = uni.upx2px(350);//350是定义消息图片最大宽度
			let maxH = uni.upx2px(350);//350是定义消息图片最大高度
			if(content.w>maxW||content.h>maxH){
				let scale = content.w/content.h;
				content.w = scale>1?maxW:maxH*scale;
				content.h = scale>1?maxW/scale:maxH;
			}
			return content;
		},
		// 选择图片发送
		chooseImage(){
			if (!this.can_send) {
				return;
			}
			if (this.isEndTime) {
				return;
			}
			this.getImage('album');
		},
		//拍照发送
		camera(){
			this.getImage('camera');
		},
		//选照片 or 拍照
		getImage(type){
			uni.chooseImage({
				sourceType:['album','camera'],
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				count: 1,
				success: (res)=>{
					let path = res.tempFilePaths[0];
					uploadImage(path,'','wechat/', res => {
						// that.avatarUrl = res.imgUrl;
						// that.imgName = res.imgName
						this.sendMsg(res.imgName,'img');
					});
					// for(let i=0;i<res.tempFilePaths.length;i++){
					// 	uni.getImageInfo({
					// 		src: res.tempFilePaths[i],
					// 		success: (image)=>{
					// 			console.log(image.width);
					// 			console.log(image.height);
					// 			// let msg = {url:res.tempFilePaths[i],w:image.width,h:image.height};
					// 			this.sendMsg(res,'img');
					// 		}
					// 	});
					// }
				}
			});
		},
		//获取焦点，如果不是选表情ing,则关闭抽屉
		textareaFocus(){
			if(this.popupLayerClass=='showLayer' && this.hideMore == false){
				this.hideDrawer();
			}
		},
		// 发送消息
		sendMsg(content,type){
			console.log('this.group_id'+this.group_id)
			console.log(typeof this.group_id)
			let message
			if(type=='text'){
				message = this.$tim.createTextMessage({
					to: this.group_id,
					conversationType: this.$TIM.TYPES.CONV_GROUP,
					cloudCustomData: 0+','+2,
					payload: {
						text: content.text
					}
				});
			} else if(type=='img'){
				// message = this.$tim.createImageMessage({
				// 	to: this.group_id,
				// 	conversationType: this.$TIM.TYPES.CONV_GROUP,
				// 	payload: { file: content }
				// })
				message = this.$tim.createCustomMessage({
					to: this.group_id,
					cloudCustomData: 0+','+2,
					conversationType: this.$TIM.TYPES.CONV_GROUP,
					payload: {
						data: content,
						description: 'image',
						extension: ''
					}
				})
			}
			this.$store.commit('pushCurrentMessageList', message)
			let pomise = this.$tim.sendMessage(message)
			pomise.then(res=>{
				this.$nextTick(()=> {
					// 滚动到底
					this.scrollToView = res.data.message.ID
				});
			})	
		},
	}
};
</script>

<style lang="scss">
.is_show {
	display: flex;
	align-items: center;
	justify-content: center;
	text-align: center;
	margin-top: -20rpx;
	position: relative;
	z-index: 999;
}
.is_show1 {
	display: flex;
	align-items: center;
	justify-content: center;
	text-align: center;
	position: relative;
	z-index: 999;
}
.is_show_dian {
	width: 16rpx;
	height: 16rpx;
	background-color: #a0e0ae;
	border-radius: 50%;
}
.is_show_text {
	color: #999;
	text-align: center;
	font-family: Alibaba PuHuiTi 2;
	font-size: 24rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
	text-transform: capitalize;
	margin-left: 10rpx;
}
.scroll_view {
	width: 100%;
	height: calc(100vh - 250rpx);
}
.bottom_view {
	width: 100%;
	height: 150rpx;
	background-color: #fff;
	padding: 0 30rpx;
	box-sizing: border-box;
	display: flex;
	justify-content: space-between;
	align-items: center;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
}

.bottom_view_input::placeholder {
	color: #b2b2b2;
}
.bottom_view_input {
	width: 78%;
	padding: 0 20rpx;
	height: 96rpx;
	border-radius: 96rpx;
	box-sizing: border-box;
	border: 1px solid #f0f0f0;
	color: #333;
	font-family: Alibaba PuHuiTi 2;
	font-size: 30rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
}
.bottom_view_btn {
	width: 20%;
	background-color: #ccc;
	height: 69rpx;
	border-radius: 69rpx;
	text-align: center;
	line-height: 69rpx;
	font-size: 28rpx;
	color: #fff;
}
.bottom_view_btn_active {
	width: 20%;
	background-color: #3570f6;
	height: 69rpx;
	border-radius: 69rpx;
	text-align: center;
	line-height: 69rpx;
	font-size: 28rpx;
	color: #fff;
}
.dialogue_list {
	width: 100%;
	height: 100%;
	padding: 0 30rpx;
	box-sizing: border-box;
}
.dialogue_list_item {
	max-width: 570rpx;
	margin-top: 40rpx;
}
.dialogue_list_left {
	position: relative;
	display: flex;
}
.dialogue_list_left_img {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: #f7f7f9;
}

.dialogue_list_left_text {
	padding: 30rpx;
	box-sizing: border-box;
	border-radius: 0 40rpx 40rpx 40rpx;
	background-color: #f7f7f9;
	color: #333;
	font-family: Alibaba PuHuiTi 2;
	font-size: 30rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
	display: inline-block;
	margin-left: 15rpx;
}
.dialogue_list_left_text_tishi {
	color: var(--unnamed, #3570f6);
	font-family: Alibaba PuHuiTi 2;
	font-size: 30rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
}
.list_right {
	display: flex;
	flex-direction: row-reverse;
}
.dialogue_list_right {
	padding: 30rpx;
	box-sizing: border-box;
	color: #fff;
	text-align: right;
	font-family: Alibaba PuHuiTi 2;
	font-size: 30rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
	border-radius: 40rpx 40rpx 0rpx 40rpx;
	background: var(--unnamed, #3570f6);
}
.list_left {
	/* margin-top: 24rpx; */
}
.scroll_view_view {
	width: 100%;
	height: auto;
	padding-bottom: 150rpx;
}
.dialogue_list_left_ff {
	/* display: flex;
	align-items: center; */
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
}
.left_name {
	color: #63686f;
	text-align: justify;
	font-family: Alibaba PuHuiTi 2;
	font-size: 24rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
	text-transform: capitalize;
	margin-left: 20rpx;
}
.item_flex {
	display: flex;
	align-items: center;
	position: absolute;
	bottom: 0;
	right: -100rpx;
}
.fuzhi_img {
	width: 34rpx;
	height: 34rpx;
}
.fuzhi_text {
	color: #999;
	font-family: Alibaba PuHuiTi 2;
	font-size: 28rpx;
	font-style: normal;
	font-weight: 400;
}
/deep/.uni-scroll-view-content {
	height: auto !important;
}
.time {
	@include flex;
	align-items: center;
	margin-left: 20rpx;
	padding: 3rpx 10rpx;
	border-radius: 100rpx;
	background: #eee;
	position: fixed;
	right: 40rpx;
	bottom: 204rpx;
	&__jieshu {
		color: #666;
		font-size: 24rpx;
		font-weight: 400;
	}
	&__custom {
		// margin-top: 4px;
		width: 30rpx;
		height: 30rpx;
		color: #333;
		text-align: center;
		border-radius: 4px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;

		&__item {
			color: #666;
			font-size: 12px;
			text-align: center;
		}
	}

	&__doc {
		color: #666;
		padding: 0px 4rpx;
	}

	&__item {
		color: #606266;
		font-size: 15px;
		margin-right: 4px;
	}
}
</style>
